<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录 - 超级AI面试官</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .login-container {
            background: white;
            padding: 40px;
            border-radius: 20px;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 400px;
            animation: slideUp 0.6s ease-out;
        }

        @keyframes slideUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .logo {
            text-align: center;
            margin-bottom: 30px;
        }

        .logo h1 {
            color: #333;
            font-size: 28px;
            margin-bottom: 10px;
        }

        .logo p {
            color: #666;
            font-size: 16px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 500;
        }

        .form-group input {
            width: 100%;
            padding: 15px;
            border: 2px solid #e1e5e9;
            border-radius: 10px;
            font-size: 16px;
            transition: all 0.3s ease;
            background: #f8f9fa;
        }

        .form-group input:focus {
            outline: none;
            border-color: #667eea;
            background: white;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .login-btn {
            width: 100%;
            padding: 15px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s ease;
            margin-bottom: 20px;
        }

        .login-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
        }

        .login-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .divider {
            text-align: center;
            margin: 25px 0;
            position: relative;
            color: #999;
        }

        .divider::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 0;
            right: 0;
            height: 1px;
            background: #e1e5e9;
        }

        .divider span {
            background: white;
            padding: 0 15px;
        }

        .register-link {
            text-align: center;
        }

        .register-link a {
            color: #667eea;
            text-decoration: none;
            font-weight: 500;
        }

        .register-link a:hover {
            text-decoration: underline;
        }

        .error-message {
            background: #fee;
            color: #c33;
            padding: 10px;
            border-radius: 8px;
            margin-bottom: 15px;
            border: 1px solid #fcc;
            display: none;
        }

        .success-message {
            background: #efe;
            color: #3c3;
            padding: 10px;
            border-radius: 8px;
            margin-bottom: 15px;
            border: 1px solid #cfc;
            display: none;
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="logo">
            <h1>🤖 超级AI面试官</h1>
            <p>智能招聘，精准匹配</p>
        </div>

        <div id="error-message" class="error-message"></div>
        <div id="success-message" class="success-message"></div>

        <form id="login-form">
            <div class="form-group">
                <label for="username">用户名</label>
                <input type="text" id="username" name="username" required placeholder="请输入用户名">
            </div>

            <div class="form-group">
                <label for="password">密码</label>
                <input type="password" id="password" name="password" required placeholder="请输入密码">
            </div>

            <button type="submit" class="login-btn" id="login-btn">登录</button>
        </form>

        <div class="divider">
            <span>还没有账号？</span>
        </div>

        <div class="register-link">
            <a href="/register">立即注册</a>
        </div>
        

    </div>

    <!-- 引入认证管理脚本 -->
    <script src="/js/auth.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const loginForm = document.getElementById('login-form');
            const loginBtn = document.getElementById('login-btn');
            const errorMessage = document.getElementById('error-message');
            const successMessage = document.getElementById('success-message');

            function showError(message) {
                errorMessage.textContent = message;
                errorMessage.style.display = 'block';
                successMessage.style.display = 'none';
            }

            function showSuccess(message) {
                successMessage.textContent = message;
                successMessage.style.display = 'block';
                errorMessage.style.display = 'none';
            }

            function hideMessages() {
                errorMessage.style.display = 'none';
                successMessage.style.display = 'none';
            }

            // 智能token验证函数
            async function validateTokenSafely() {
                const token = localStorage.getItem('token');
                
                // 如果没有token，直接返回false
                if (!token) {
    
                    return false;
                }

                // 检查是否正在验证中，避免重复验证
                if (window.tokenValidating) {
                    return false;
                }

                // 检查最近是否验证过失败，避免频繁验证
                const lastValidationFailed = sessionStorage.getItem('tokenValidationFailed');
                if (lastValidationFailed) {
                    const failTime = parseInt(lastValidationFailed);
                    const now = Date.now();
                    // 如果5分钟内验证失败过，不再自动验证
                    if (now - failTime < 5 * 60 * 1000) {
                        return false;
                    }
                }

                try {
                    window.tokenValidating = true;

                    
                    const response = await fetch('/api/users/check', {
                        method: 'GET',
                        headers: {
                            'Authorization': 'Bearer ' + token,
                            'Content-Type': 'application/json'
                        }
                    });

                    if (response.ok) {
                        const userData = await response.json();
                        if (userData.valid) {

                            // 清除失败记录
                            sessionStorage.removeItem('tokenValidationFailed');
                            return true;
                        }
                    }
                    
                    throw new Error('Token validation failed');
                    
                } catch (error) {

                    // 记录验证失败时间
                    sessionStorage.setItem('tokenValidationFailed', Date.now().toString());
                    // 清除无效token
                    localStorage.removeItem('token');
                    localStorage.removeItem('username');
                    return false;
                } finally {
                    window.tokenValidating = false;
                }
            }

            // 页面加载时进行智能token检查
            async function checkAutoLogin() {
                // 检查URL参数，如果有强制登录参数，跳过自动登录
                const urlParams = new URLSearchParams(window.location.search);
                if (urlParams.get('force') === 'true') {
                    return;
                }

                const isValid = await validateTokenSafely();
                if (isValid) {
                    showSuccess('检测到有效登录状态，正在跳转...');
                    setTimeout(() => {
                        window.location.href = '/';
                    }, 1000);
                }
            }

            // 执行自动登录检查
            checkAutoLogin();

            loginForm.addEventListener('submit', async function(e) {
                e.preventDefault();
                hideMessages();

                const username = document.getElementById('username').value.trim();
                const password = document.getElementById('password').value.trim();

                if (!username || !password) {
                    showError('请填写完整的用户名和密码');
                    return;
                }

                loginBtn.disabled = true;
                loginBtn.textContent = '登录中...';

                try {

                    const response = await fetch('/api/users/login', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            username: username,
                            password: password
                        })
                    });

                    // 获取响应文本来调试
                    const responseText = await response.text();
                    
                    let data;
                    try {
                        data = JSON.parse(responseText);
                    } catch (parseError) {
                        console.error('JSON解析错误:', parseError);
                        showError('服务器响应格式错误');
                        return;
                    }

                    if (response.ok && data.success) {
                        // 使用AuthManager保存登录状态
                        if (window.authManager) {
                            window.authManager.setLoggedIn(data.token, data.user.username);
                        } else {
                            // 兼容性处理
                            localStorage.setItem('token', data.token);
                            localStorage.setItem('username', data.user.username);
                        }
                        
                        // 清除之前的验证失败记录
                        sessionStorage.removeItem('tokenValidationFailed');
                        
                        showSuccess('登录成功，正在跳转...');
                        
                        // 检查是否有重定向URL
                        const urlParams = new URLSearchParams(window.location.search);
                        const redirectUrl = urlParams.get('redirect') || '/';
                        
                        // 延迟跳转，让用户看到成功消息
                        setTimeout(() => {
                            window.location.href = redirectUrl;
                        }, 1500);
                    } else {
                        showError(data.message || '登录失败，请检查用户名和密码');
                    }
                } catch (error) {
                    console.error('登录错误:', error);
                    showError('网络错误，请稍后重试');
                } finally {
                    loginBtn.disabled = false;
                    loginBtn.textContent = '登录';
                }
            });
        });
        

    </script>
</body>
</html> 